package com.zhangx.study.demo.rpc.server;

import com.zhangx.study.demo.rpc.server.model.User;
import com.zhangx.study.demo.rpc.server.service.IUserService;
import com.zhangx.study.demo.rpc.server.service.UserServiceImpl;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName RpcServer
 * @Description TODO
 * @Author zhangx
 * @Date 2020/10/12 8:18
 **/
public class RpcServer {

    private static boolean running = true;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (running){
                Socket socket = serverSocket.accept();
                process(socket);
                socket.close();
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void process(Socket socket){
        try {
            InputStream in = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(in);

            OutputStream out = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);

            int id = dataInputStream.readInt();
            IUserService userService = new UserServiceImpl();
            User user = userService.findUserById(id);

            dataOutputStream.writeInt(user.getAge());
            dataOutputStream.writeUTF(user.getName());
            dataOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
